<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>home</title>
    <link rel="stylesheet" th:href="@{/static/lib/layui-v2.5.4/css/layui.css}" media="all">
    <script>
        const PATH = "[[${#httpServletRequest.getContextPath()}]]";
    </script>

    <!-- 避免Thymeleaf异常 -->
    <script type="text/javascript" th:inline="javascript"></script>


    <style>::-webkit-scrollbar {
        display: none;
    }

    html, body {
        overflow: hidden;
        margin: 0;
    }
    </style>
</head>
<body id="iosiframe">

<div id='head_div'>
    <div class="layui-form layui-form-pane" action="" onsubmit="return false">
        <div class="layui-form-item">
            <label class="layui-form-label" title="起始时间"><span style="color:red;">*</span>起始时间</label>
            <div class="layui-input-block">
                <input type="text" id="time" class="layui-input" onchange="getEnv();">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">环境</label>
                <div class="layui-input-inline">
                    <select id="environment">
                        <option value="">ALL</option>
                    </select>
                </div>
                <button class="layui-btn layui-btn2" id="search" onclick="showData(1)">搜索</button>
            </div>
        </div>
    </div>
</div>
<div id='body_div'>
    <div id="mountNode"></div>
</div>

<script>document.body.clientHeight;</script>
<script th:src="@{/static/public/js/g6/g6.js}"></script>
<script th:src="@{/static/public/js/g6/dagre.min.js}"></script>

<script src="/static/layui/layui.all.js" th:src="@{/static/lib/layui-v2.5.4/layui.all.js}"></script>
<script th:src="@{/static/lib/jquery-3.4.1/jquery-3.4.1.min.js}"></script>

<script>
    let form, layer, laydate;
    layui.use(['layer', 'form', 'laydate'], function () {
        form = layui.form, layer = layui.layer, laydate = layui.laydate;
        laydate.render({
            elem: '#time'
            , type: 'datetime'
            , range: true
            , format: 'yyyy-MM-dd HH:mm:ss'
            , done: function (time) {
                if (time === '') {
                    return false;
                }
                let start, end;
                time = time.split(' - ');
                if (time != null && time.length === 2) {
                    start = time[0].replace(' ', 'T') + '.000Z';
                    end = time[1].replace(' ', 'T') + '.000Z';
                }
                $.post({
                    url: '/services/getEnv',
                    data: {
                        start: encodeURIComponent(start),
                        end: encodeURIComponent(end)
                    },
                    success: function (res) {
                        if (res.success) {
                            $("#environment").html("<option value=''>ALL</option>");
                            let data = res.data;
                            data = data.replace('[', '').replace(']', '').replaceAll('\"', '').replaceAll('\'', '');
                            data = data.split(',');
                            if (data.length > 0) {
                                for (let i in data) {
                                    if (data.hasOwnProperty(i)) {
                                        $("#environment").append(new Option(data[i], data[i]));
                                    }
                                }
                                // getParam();
                            }
                            form.render();
                        }
                    }
                });
            }
        });
    });
</script>
<script type="text/javascript" th:inline="none">
    function showData() {
        init();
        let time = $("#time").val();
        if (time === '') {
            layer.msg('请选择起始时间!', {icon: 2});
            return false;
        }
        let start, end;
        time = time.split(' - ');
        if (time != null && time.length === 2) {
            start = time[0].replace(' ', 'T') + '.000Z';
            end = time[1].replace(' ', 'T') + '.000Z';
        }
        let environment = $("#environment").val();

        $.post({
            url: '/services/map',
            data: {
                start: encodeURIComponent(start),
                end: encodeURIComponent(end),
                environment: environment
            },
            success: function (res) {
                let data = [];
                if (res.success) {
                    if (res.data.elements === '') {
                        data = [];
                    } else {
                        data = res.data.elements;
                    }
                }
                let list = {};
                let nodes = [];
                let edges = [];

                if (data.length > 0) {
                    let d, all = {};
                    for (let i in data) {
                        if (data.hasOwnProperty(i)) {
                            d = data[i]['data'];
                            if (d.target !== undefined) {
                                if (all[d['sourceData']['id']] === undefined) {
                                    all[d['sourceData']['id']] = 1;
                                    // console.log(d['sourceData']['id'] + '--' + d['sourceData']['service']['name']);
                                    nodes.push({
                                        id: d['sourceData']['id']
                                        , label: d['sourceData']['service']['name']
                                    });
                                }
                                edges.push({
                                    source: d['sourceData']['id']
                                    , target: d['targetData']['id']
                                });
                                // console.log(d['sourceData']['id'] + '-->' + d['targetData']['id']);
                            } else {
                                if (all[d['id']] === undefined) {
                                    all[d['id']] = 1;
                                    nodes.push({
                                        id: d['id']
                                        , label: (d['service'] === undefined ? d['label'] : d['service']['name'])
                                    });
                                    // console.log(d['id'] + '--' + (d['service'] === undefined ? d['label'] : d['service']['name']));
                                }
                            }
                        }
                    }
                    list['nodes'] = nodes;
                    list['edges'] = edges;
                }

                if (data.length > 0) {
                    // console.log(list);
                    show(list);
                }
            }
        });
    }

    function show(data) {
        var _extends = Object.assign || function (target) {
            for (var i = 1; i < arguments.length; i++) {
                var source = arguments[i];
                for (var key in source) {
                    if (Object.prototype.hasOwnProperty.call(source, key)) {
                        target[key] = source[key];
                    }
                }
            }
            return target;
        };

        /**
         * 本案例演示如何使用G6自定义流程图：
         * 1、如何使用G6绘制流程图；
         * 2、如何在贝塞尔曲线上面自定义icon；
         * 3、如何响应贝塞尔曲线上icon的点击事件。
         *
         * by 一之
         *
         */

        /**
         * node 特殊属性
         */
        var nodeExtraAttrs = {
            begin: {
                fill: "#9FD4FB"
            },
            end: {
                fill: "#C2E999"
            }
        };

        /**
         * 自定义节点
         */
        G6.registerNode("node", {
            drawShape: function drawShape(cfg, group) {
                var rect = group.addShape("rect", {
                    attrs: _extends({
                        x: -75,
                        y: -25,
                        width: 150,
                        height: 50,
                        radius: 4,
                        fill: "#009688",
                        fillOpacity: 1
                    }, nodeExtraAttrs[cfg.type])
                });
                return rect;
            },
            // 设置状态
            setState: function setState(name, value, item) {
                var group = item.getContainer();
                var shape = group.get("children")[0]; // 顺序根据 draw 时确定

                if (name === "selected") {
                    if (value) {
                        shape.attr("fill", "#0ff683");
                    } else {
                        shape.attr("fill", "#6bffca");
                    }
                }
            },

            getAnchorPoints: function getAnchorPoints() {
                return [[0, 0.5], [1, 0.5]];
            }
        }, "single-shape");

        /**
         * 自定义 edge 中心关系节点
         */
        G6.registerNode("statusNode", {
            drawShape: function drawShape(cfg, group) {
                var circle = group.addShape("circle", {
                    attrs: {
                        x: 0,
                        y: 0,
                        r: 6,
                        fill: cfg.active ? "#AB83E4" : "#ccc"
                    }
                });
                return circle;
            }
        }, "single-shape");

        /**
         * 自定义带箭头的贝塞尔曲线 edge
         */
        G6.registerEdge("line-with-arrow", {
            itemType: "edge",
            draw: function draw(cfg, group) {
                var startPoint = cfg.startPoint;
                var endPoint = cfg.endPoint;
                var centerPoint = {
                    x: (startPoint.x + endPoint.x) / 2,
                    y: (startPoint.y + endPoint.y) / 2
                };
                // 控制点坐标
                var controlPoint = {
                    x: (startPoint.x + centerPoint.x) / 2,
                    y: startPoint.y
                };

                // 为了更好的展示效果, 对称贝塞尔曲线需要连到箭头根部
                var path = group.addShape("path", {
                    attrs: {
                        path: [["M", startPoint.x, startPoint.y], ["Q", controlPoint.x + 8, controlPoint.y, centerPoint.x, centerPoint.y], ["T", endPoint.x - 8, endPoint.y], ["L", endPoint.x, endPoint.y]],
                        stroke: "#ccc",
                        lineWidth: 1.6,
                        endArrow: {
                            path: "M 4,0 L -4,-4 L -4,4 Z",
                            d: 4
                        }
                    }
                });

                // 在贝塞尔曲线中心点上添加圆形
                var source = cfg.source,
                    target = cfg.target;

                group.addShape("circle", {
                    attrs: {
                        id: "statusNode" + source + "-" + target,
                        r: 6,
                        x: centerPoint.x,
                        y: centerPoint.y,
                        fill: cfg.active ? "#AB83E4" : "#ccc"
                    }
                });

                return path;
            }
        });

        var graph = new G6.Graph({
            container: "mountNode",
            width: 1000,
            height: 800,
            layout: {
                type: 'dagre',
                rankdir: 'LR'
            },
            modes: {
                default: ['drag-canvas']
            },
            defaultNode: {
                shape: "node",
                labelCfg: {
                    style: {
                        fill: "#fff",
                        fontSize: 14
                    }
                }
            },
            defaultEdge: {
                shape: "line-with-arrow",
                style: {
                    endArrow: true,
                    lineWidth: 2,
                    stroke: "#ccc"
                }
            }
        });

        graph.data(data);
        graph.render();

        graph.on('edge:click', function (evt) {
            var target = evt.target;

            var type = target.get('type');
            if (type === 'circle') {
                // 点击边上的circle
                alert('你点击的是边上的圆点');
            }
        });
    }

    /**
     * 获取环境列表
     * @returns
     */
    function getEnv() {
        let time = $("#time").val();
        if (time === '') {
            layer.msg('请选择起始时间!', {icon: 2});
            return false;
        }
        let start, end;

        time = time.split(' - ');
        if (time != null && time.length === 2) {
            start = time[0].replace(' ', 'T') + '.000Z';
            end = time[1].replace(' ', 'T') + '.000Z';
        }
        $.post({
            url: '/services/getEnv',
            data: {
                start: encodeURIComponent(start),
                end: encodeURIComponent(end)
            },
            success: function (res) {
                console.log(res);
            }
        });
    }

    /**
     * 获取服务、探针列表
     */
    /*function getParam() {
        let time = $("#time").val();
        if (time === '') {
            return false;
        }
        let start, end;
        time = time.split(' - ');
        if (time != null && time.length === 2) {
            start = time[0].replace(' ', 'T') + '.000Z';
            end = time[1].replace(' ', 'T') + '.000Z';
        }
        let environment = $("#environment").val();
        let uiFilters = {environment: environment};

        $.post({
            url: '/services/getParam',
            data: {
                start: start,
                end: end,
                uiFilters: encodeURIComponent(JSON.stringify(uiFilters)),
                filterNames: encodeURIComponent('["host","agentName"]')
            },
            success: function (res) {
                if (res.success) {
                    let data = res.data;
                    $("#host").html("<option value=''>请选择服务器主机名</option>");
                    $("#agentName").html("<option value=''>请选择探针类型</option>");
                    if (data.length > 0) {
                        for (let i in data) {
                            if (data.hasOwnProperty(i)) {
                                let temp = data[i];
                                let ops = temp['options'];
                                if (temp['name'] === 'host') {
                                    if (ops.length > 0) {
                                        for (let o in ops) {
                                            if (ops.hasOwnProperty(o)) {
                                                $("#host").append(new Option(ops[o]['name'] + "(" + ops[o]['count'] + ")", ops[o]['name']))
                                            }
                                        }
                                    }
                                }
                                if (temp['name'] === 'agentName') {
                                    if (ops.length > 0) {
                                        for (let o in ops) {
                                            if (ops.hasOwnProperty(o)) {
                                                $("#agentName").append(new Option(ops[o]['name'] + "(" + ops[o]['count'] + ")", ops[o]['name']))
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    layui.form.render();
                }
            }
        });
    }*/

    function init() {
        let ua = navigator.userAgent.toLowerCase();
        let screenWidth = window.screen.width;
        if (!/iphone|ipad|ipod/.test(ua)) {
            $("#iosiframe").attr("scrolling", "auto");
        } else {
            $('#iosiframe').width(screenWidth + 'px');
        }

        $("body").css({
            "height": $(window).height() - 15
        });
        $("#body_div").css({
            "height": $("body").height() - $("#head_div").height() - 10
        });
        // tableHeight = $("#body_div").height() - 15;
    }

    $(window).resize(function () {
        init();
    });
</script>
</body>
</html>
